import { http } from "@/utils/http";
import type { AjaxResult } from "./types";
import { baseUrlApi } from "./utils";

// 定义Category接口，用于描述类别数据结构
interface CategoryDTO {
  categoryId: number;
  categoryName: string;
  parentName: string;
  parentId: number | null;
  createTime: Date; // 添加创建时间字段
  children?: CategoryDTO[];
}

interface ParentDTO {
  categoryId: number;
  categoryName: string;
  parentName: string;
  parentId: number;
}

// 定义CategoryForm接口，用于描述新增或修改类别时的表单数据结构
interface CategoryForm {
  categoryId?: number;
  categoryName: string;
  parentName?: string;
  parentId: number | null;
}

// 定义QueryParams接口，用于描述查询参数数据结构
interface QueryParams {
  pageNum: number;
  pageSize: number;
  parentName?: string;
  categoryName?: string;
  categoryId?: number;
  parentId?: number | null;
}

// 类别表单数据
interface RuleForm {
  categoryId?: number;
  parentId?: number;
  categoryName?: string;
  parentName?: string;
}

interface addForm {
  categoryId?: number;
  parentId?: number;
  categoryName?: string;
}

// 查询所有类别
export const listAllCategory = () => {
  return http.request<AjaxResult>("get", baseUrlApi("/category/tree"));
};

// 查询父类别
export const listParent = () => {
  return http.request<AjaxResult>("get", baseUrlApi("/category/getParent"));
};

// 根据id查询类别
export const getCategoryById = (categoryId: number) => {
  return http.request<AjaxResult>(
    "get",
    baseUrlApi(`/category/getById/${categoryId}`)
  );
};

// 根据id查询类别
export const getCategoryByName = (categoryName: string) => {
  return http.request<AjaxResult>(
    "get",
    baseUrlApi(`/category/getByName/${categoryName}`)
  );
};

// 新增类别
export const addCategory = (data: CategoryForm) => {
  return http.request<AjaxResult>("post", baseUrlApi("/category"), { data });
};

// 修改类别
export const updateCategory = (data: CategoryForm) => {
  return http.request<AjaxResult>("put", baseUrlApi("/category"), { data });
};

// 删除类别
export const deleteCategory = (categoryId: number) => {
  return http.request<AjaxResult>(
    "delete",
    baseUrlApi(`/category/${categoryId}`)
  );
};

// 批量删除类别
export const deleteCategoryBatch = (categoryIds: number[]) => {
  return http.request<AjaxResult>(
    "delete",
    baseUrlApi(`/category/delBatch/${categoryIds.join(",")}`)
  );
};

// 分页查询类别列表
export const listCategoryByPage = (query: QueryParams) => {
  return http.request<AjaxResult>("get", baseUrlApi("/category/page"), {
    params: query
  });
};

// 查询所有类别
export const listCategoryByTree = () => {
  return http.request<AjaxResult>("get", baseUrlApi("/category/tree"));
};

// 重新导出类型
export type {
  CategoryDTO,
  CategoryForm,
  QueryParams,
  ParentDTO,
  RuleForm,
  addForm
};
